<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 生产计划
 *
 * @icon fa fa-circle-o
 */
class ClothmakingPlan extends Backend
{

    /**
     * ClothmakingPlan模型对象
     * @var \app\admin\model\ClothmakingPlan
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\ClothmakingPlan;
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        
        // 检查当前状态是否为已完成
        if ($row['status'] == 'completed') {
            // 如果状态已经是完成，不允许修改为其他状态
            if (isset($params['status']) && $params['status'] != 'completed') {
                $this->error(__('该计划已完成，不允许修改为其他状态'));
            }
            // 如果状态已经是完成，不再进行库存操作
            // 直接执行后续的更新操作
        } else {
            // 如果状态改为已完成，检查原材料是否足够
            if ($params['status'] == 'completed') {
            $quantity = $params['quantity'];
            $recipe_id = $row['recipe_id'];
            if (empty($recipe_id) || empty($quantity)) {
                $this->error(__('配方 ID 和数量不能为空'));
            }

            // 查询配方所需的原材料
            $recipe = \app\admin\model\ClothmakingPlan::with('recipe')->find($ids);
            $ingredientDetails = json_decode($recipe->recipe->ingredient_details, true);

            // 检查每个原材料的库存
            foreach ($ingredientDetails as $ingredientName => $requiredQuantity) {
                // 计算需要的总数量（生产数量 × 配方所需数量）
                $totalRequiredQuantity = $quantity * $requiredQuantity;

                // 根据原材料名称查询原材料ID
                $rawMaterial = \app\admin\model\ClothmakingRaw::where('name', $ingredientName)->find();

                if (!$rawMaterial) {
                    $this->error(__('原材料 %s 不存在', $ingredientName));
                }

                // 查询该原材料的总库存
                $totalInventory = \app\admin\model\MaterialWarehouse::where('material_id', $rawMaterial->id)
                    ->sum('quantity');

                // 检查库存是否足够
                if ($totalInventory < $totalRequiredQuantity) {
                    $this->error(__('原材料 %s 库存不足，需要 %s%s，当前库存 %s%s',
                        $ingredientName, $totalRequiredQuantity, $rawMaterial->unit, $totalInventory,
                        $rawMaterial->unit));
                }
                
                // 记录需要扣减的原材料信息，用于后续扣减
                $materialsToDeduct[] = [
                    'material_id' => $rawMaterial->id,
                    'material_name' => $ingredientName,
                    'quantity' => $totalRequiredQuantity,
                    'unit' => $rawMaterial->unit
                ];
            }
        }

        // 如果状态是已完成，准备扣减原材料库存
        if ($params['status'] == 'completed' && !empty($materialsToDeduct)) {
            // 扣减原材料库存（按先进先出原则）
            foreach ($materialsToDeduct as $material) {
                $remainingQuantity = $material['quantity'];
                $warehouseRecords = \app\admin\model\MaterialWarehouse::where('material_id', $material['material_id'])
                    ->order('create_time ASC')
                    ->select();
                foreach ($warehouseRecords as $record) {
                    if ($remainingQuantity <= 0) break;
                    
                    $deductQuantity = min($remainingQuantity, $record->quantity);
                    // 如果完全扣减这条记录，删除记录
                    if ($deductQuantity >= $record->quantity) {
                        $deleteResult = $record->delete();
                        if ($deleteResult === false) {
                            Db::rollback();
                            $this->error(__('原材料 %s 库存扣减失败', $material['material_name']));
                        }
                    } else {
                        // 部分扣减，更新记录
                        $record->quantity -= $deductQuantity;
                        $updateResult = $record->save();
                        if ($updateResult === false) {
                            Db::rollback();
                            $this->error(__('原材料 %s 库存扣减失败', $material['material_name']));
                        }
                    }
                    
                    $remainingQuantity -= $deductQuantity;
                }
                
                if ($remainingQuantity > 0) {
                    Db::rollback();
                    $this->error(__('原材料 %s 库存扣减异常，剩余 %s%s 未扣减', 
                        $material['material_name'], $remainingQuantity, $material['unit']));
                }
            }
        }
        // 闭合 else 块
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 打印生产计划
     */
    public function print($ids = "")
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取产品信息
        $product = \think\Db::name('clothmaking_product')->where('id', $row['product_id'])->find();
        if (!$product) {
            $this->error(__('Product not found'));
        }
        
        // 格式化日期：年月日，年份用后两位
        $date = date('ymd', $row['createtime']);
        
        // 格式化产品ID：4位数，不足前面补0
        $productId = str_pad($row['product_id'], 4, '0', STR_PAD_LEFT);
        
        // 格式化计划ID：4位数，不足前面补0
        $planId = str_pad($row['id'], 4, '0', STR_PAD_LEFT);
        
        // 产品型号
        $productModel = $product['alias']; // 使用alias字段作为产品型号
        
        // 生成打印内容
        $printContent = $date . '-' . $productId . '-' . $productModel . '-' . $planId;
        
        $this->view->assign('printContent', $printContent);
        $this->view->assign('row', $row);
        $this->view->assign('product', $product);
        
        return $this->view->fetch();
    }

}
